<?PHP
include_once "ini.php";
$x_scene = 10;
$z_scene = 10;
$origine_x = ($x_scene/2)-$x_scene;
$origine_z = ($z_scene/2)-$z_scene;
$pas = 2;
dbconnect();
$i_case = 0;
for ($i = $origine_x; $i < $x_scene/2; $i += $pas)
{
    $xmin = $i;
    $xmax = $i+$pas;
    for ($j = $origine_z; $j < $z_scene/2; $j += $pas)
    {
        $zmin = $j;
        $zmax = $j+$pas;

        $sql = "SELECT COUNT(*),AVG(coord_x),AVG(coord_z) FROM images WHERE coord_x < '".$xmax."' AND coord_x > '".$xmin."' AND coord_z < '".$zmax."' AND coord_z > '".$zmin."';";
        $requete = mysql_query($sql);
        if (!$requete)
        {
            echo "SQL error : ", $sql;
            exit ;
        }
        else
        {

            $result = mysql_fetch_row($requete);

            $nb_point = $result[0];
            $somme_x = $result[1];
            $somme_z = $result[2];
            if ($nb_point != 0)
            {
                $barycentre = $somme_x/$nb_point.",0,".$somme_z/$nb_point;
            }
			else{
				$barycentre = $xmin+$pas/2;
				$barycentre .= ",0,";
				$barycentre .= $zmin+($pas/2);
				
			}

        }



        $sql2 = "INSERT INTO quadrillage VALUES ('".$id_case."', '".$xmin."', '".$xmax."', '".$zmin."', '".$zmax."', '".$nb_point."', '".$somme_x."', '".$somme_z."', '".$barycentre."');";
        $result = mysql_query($sql2);
        if (!$result)
        {
            echo "SQL error : ", $sql2;
            exit ;
        }
        else
        {
            echo "Quadrillage fait.";
			$id_case++;
        }
    }
    
}

$sql = "SELECT * FROM quadrillage;";
$req = mysql_query($sql);

if (!$req)
{
    echo "SQL error : ", $sql;
    exit ;
}
else
{
    $file = "../quadrillage.txt";
    $fp = fopen($file, "w");

    while ($tab = mysql_fetch_assoc($req))
    {
	    $ligne = $tab['id_case']."	".$tab['nb_point']."	".$tab['barycentre']."\n";
        fputs($fp, $ligne);
    }
    fclose($fp);
}



dbclose();
?>
